package com.sgb.kjwl.view.ui.activity.self.company

import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.util.SparseArray
import android.view.View
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.blankj.utilcode.util.SpanUtils
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.sgb.capital.callback.Constants
import com.sgb.capital.callback.OnZTabSelectedListener
import com.sgb.capital.callback.ZMessageEvent
import com.sgb.capital.model.Bean
import com.sgb.capital.model.CommodityBean
import com.sgb.capital.utils.Utils

import com.sgb.capital.view.ui.fragment.CommodityFragment
import com.sgb.kjwl.AppActivity
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.ActivityEnquiryBinding
import com.sgb.kjwl.di.self.DaggerSelfComponent
import com.sgb.kjwl.di.self.SelfModule
import com.sgb.kjwl.view.ui.fragment.manage.OtherInquiryFragment
import com.sgb.kjwl.view.ui.fragment.self.company.AgentEnquiryFragment
import com.sgb.kjwl.viewmodel.self.company.EnquiryViewModel
import com.swgk.core.base.di.AppComponent
import com.swgk.core.util.PickSelectEntity
import com.swgk.core.util.SharedPreferenceUtil
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.util.*
import javax.inject.Inject

/**
 * 询价列表
 */
class AgentEnquiryActivity : AppActivity() {

    private lateinit var mBinding: ActivityEnquiryBinding

    @Inject
    lateinit var mViewModel: EnquiryViewModel
    private lateinit var mAdapter: BasePagerAdapter<Fragment>
    private var mType: Int = 1
    private var mHasShopPermission = false
    private val mTitles = arrayOf("收到的询价", "发起的询价")
    private var mBean: Bean? = null
    private var mPosition: Int = 0
    private lateinit var mPickSelectEntity: List<PickSelectEntity<Any>>
    private var mReceiveFragments = ArrayList<Fragment>()    // 收到的询价fragment集合
    private var mInitiateFragments = ArrayList<Fragment>() //  // 发起的询价fragment集合

    companion object {
        const val KEY_TYPE = "key_type"
        const val KEY_SHOP_PERMISSION = "key_shop_permission"
        fun launch(context: Context, type: Int, hasShopPermission: Boolean) {
            val intent = Intent(context, AgentEnquiryActivity::class.java)
            intent.putExtra(KEY_TYPE, type)
            intent.putExtra(KEY_SHOP_PERMISSION, hasShopPermission)
            context.startActivity(intent)
        }
    }

    override fun setupActivityComponent(appComponent: AppComponent?) {
        super.setupActivityComponent(appComponent)
        DaggerSelfComponent.builder().appComponent(appComponent)
                .selfModule(SelfModule()).build().inject(this)
    }

    // 监听回调
    fun initListener() {
        mBinding.tablayoutFirst.addOnTabSelectedListener(object : OnZTabSelectedListener() {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                if (mType == 0 || mType == 1){
                    mPosition = tab!!.position
                    mBean!!.posFirst = tab.position
                    Utils.sendMsg(Constants.EVENT_REFRESH_COMMODITY, mBean)
                    initTabLayout(mPosition, if (mType == 0 && mPosition == 0) mPickSelectEntity.subList(1, mPickSelectEntity.size) else mPickSelectEntity)
                }
            }
        })
        mBinding.tablayout.addOnTabSelectedListener(object : OnZTabSelectedListener() {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                if (mType == 0 || mType == 1){
                    mBean!!.posSecond = tab!!.position
                    Utils.sendMsg(Constants.EVENT_REFRESH_COMMODITY, mBean)
                    val textView = tab.view.getChildAt(1) as TextView
                    textView.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                }

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                if (mType == 0 || mType == 1){
                    val textView = tab?.view?.getChildAt(1) as TextView
                    textView.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
                }
            }
        })
        mViewModel.titles.observe(this, {
            if (it != null && it.isNotEmpty()) {
                if (mType == 0 || mType == 1){
                    for (tab in it) {
                        when {
                            tab.projectscale.contains("商品") -> mInitiateFragments.add(CommodityFragment.newInstance("询价"))
                            tab.projectscale.contains("其他") -> mInitiateFragments.add(OtherInquiryFragment.newInstance())
                            else -> mInitiateFragments.add(AgentEnquiryFragment.newInstance(tab.no))
                        }
                    }
                    mReceiveFragments.addAll(if (mType == 0) mInitiateFragments.subList(1, mInitiateFragments.size) else mInitiateFragments)
                    mPickSelectEntity = it
                    initTabLayout(mPosition, if (mType == 0) it.subList(1, it.size) else it)
                } else {
                    for (tab in it) {
                        mInitiateFragments.add(AgentEnquiryFragment.newInstance(tab.no))
                    }
                    mReceiveFragments.addAll(if (mType == 0) mInitiateFragments.subList(1, mInitiateFragments.size) else mInitiateFragments)
                    initTabLayout(mPosition, if (mType == 0) it.subList(1, it.size) else it)
                }

            }
        })
    }

    override fun init() {
        super.init()
        if (mType == 1 || mType == 0 || mType == 2) { //个人和企业
            mViewModel.getTitle(mHasShopPermission)
        }
        mReceiveFragments = ArrayList<Fragment>()
        mInitiateFragments = ArrayList<Fragment>()
        initListener()
    }

    override fun initView() {
        super.initView()
        EventBus.getDefault().register(this)
        mBean = Bean()
        if (intent != null) {
            mType = intent.getIntExtra(KEY_TYPE, 1)
            mHasShopPermission = intent.getBooleanExtra(KEY_SHOP_PERMISSION, false)
        }
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_enquiry)
        mBinding.include.ivBack.setOnClickListener { finish() }
        mBinding.include.titleView.text = "询价列表"
        if (mType != 1 && mType != 0) {
            mBinding.emptyView.visibility = View.VISIBLE
            mBinding.tablayout.visibility = View.VISIBLE
            mBinding.viewPage.visibility = View.GONE
        } else {
            mBinding.emptyView.visibility = View.GONE
            mBinding.tablayout.visibility = View.VISIBLE
            mBinding.viewPage.visibility = View.VISIBLE
        }
        renderFirstTab()
    }

    private fun renderFirstTab() {
        for (item in mTitles) {
            val tab: TabLayout.Tab = mBinding.tablayoutFirst.newTab()
            tab.text = item
            mBinding.tablayoutFirst.addTab(tab)
        }
        mBinding.tablayoutFirst.getTabAt(0)!!.select()
        mBinding.tablayoutFirst.tabMode = TabLayout.MODE_FIXED
    }

    internal fun initTabLayout(position: Int, titles: List<PickSelectEntity<Any>>) {
        mAdapter = BasePagerAdapter(this)
        mBinding.viewPage.adapter = mAdapter
        mBinding.viewPage.offscreenPageLimit = titles.size
        TabLayoutMediator(mBinding.tablayout, mBinding.viewPage)
        { tab: TabLayout.Tab, position: Int -> tab.text = titles[position].projectscale }.attach()
        mAdapter.setDataList(if (position == 0 && mType == 0) mReceiveFragments else mInitiateFragments)
    }

    /**
     *设置TabItem右上角的总数量
     * @param tabIndex 要设置数量显示的TabItem的index,从0开始
     * @param count 总计的数量
     */
    fun updateTabViewCount(tabIndex: Int, count: Int) {
        if (tabIndex < 0 || tabIndex >= mBinding.tablayout.tabCount) {
            throw IndexOutOfBoundsException("input tabIndex is outside the CharSequence")
        } else {
            val totalName = mBinding.tablayout.getTabAt(tabIndex)?.view?.getChildAt(1) as TextView
            val tabName = mPickSelectEntity[tabIndex].projectscale
            SpanUtils.with(totalName)
                    .append(tabName)
                    .setFontSize(14, true)
                    .appendSpace(2)
                    .append(if (count == 0) "" else "(" + String.format("%s", if (count >= 100) String.format("%s+", 99) else count.toString()) + ")")
                    .setFontSize(12, true)
                    .create()
        }
    }

    class BasePagerAdapter<T : Fragment?>(fragmentActivity: FragmentActivity?) : FragmentStateAdapter(fragmentActivity!!) {
        var mFragmentMap = SparseArray<Fragment>()
        var mDataList: List<T>? = null
        override fun createFragment(position: Int): Fragment {
            return mDataList!![position]!!
        }

        override fun getItemCount(): Int {
            return if (mDataList != null) mDataList!!.size else 0
        }

        fun setDataList(dataList: List<T>?) {
            mDataList = dataList
            notifyDataSetChanged()
        }

        fun release() {
            mFragmentMap.clear()
        }
    }

    @Subscribe
    fun getCode(event: ZMessageEvent) {
        when (event.code) {
            Constants.EVENT_REFRESH_COUNT -> {
                updateTabViewCount(0, event.data as Int)
            }
            Constants.EVENT_CLICK -> {
                val listDTO = event.data as CommodityBean.ListDTO
                mViewModel.getPriceCheckDetail(this, listDTO.no, listDTO.status, mPosition)
            }
        }
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }
}